<?php
namespace app\common\model;

class User extends BaseModel{
	
	// 头像获取器
	public function getHeadUrlAttr($head_id = '', $data = array()){
		$head_id  = $head_id ? $head_id : $data['head_id'];
		$user_id  = $data['user_id'];
		$head_url = $this->get_user_head_url($user_id, $head_id, $data);

		return $head_url;
	}
	// 是否第三方头像获取器
	public function getIsSsoHeadAttr($head_id = '', $data = array()){
		$head_id = $head_id ? $head_id : $data['head_id'];
		if($head_id){
			return false;
		}else{
			return $data['sso_head_url'] ? true : false;
		}
	}
	public function get_user_head_url($user_id = 0, $head_id = 0, $info = []){
		if(!$user_id){
			return '';
		}
		$info    = $info ? $info : $this->field('head_id,sso_head_url,sex')->where(array('user_id' => $user_id))->find();
		$head_id = $info['head_id'];
		if(!$head_id){
			switch ($info['sex']) {
				//男头像
				case '1':
					$default_head = 'head-man-default.png';
					break;
				//女头像
				case '2':
					$default_head = 'head-woman-default.png';
					break;
				//默认头
				default:
					$default_head = 'head-man-default.png';
					break;
			}
		}
		$head_url = model('File')->get_path($head_id ? $head_id : $default_head);
		$head_url = $head_id ? $head_url : ($info['sso_head_url'] ? $info['sso_head_url'] . '.jpg' : $head_url);
		
		return $head_url;
	}
	// 用户名称获取器
	public function getShowNameAttr($user_id = '', $data = array()){
		if($user_id && !$data){
			$data = $this->field('realname,mobile,nickname')->where(array('user_id' => $user_id))->find();
		}
		if($data['realname']){
			return $data['realname'];
		}
		if($data['nickname']){
			return $data['nickname'];
		}
		if($data['mobile']){
			return substr_replace($data['mobile'], '****', 3, 4);
		}
		return '';
	}
	// 用户数据获取器
	public function getDataAttr($user_id = '', $data = array()){
		$user_id = $user_id ? $user_id : $data['user_id'];
		if(!$user_id){
			return false;
		}
		$info = model('UserData')->where(array('user_id' => $user_id))->find();

		return $info;
	}
	// 获取状态类型说明
	public function getStatusDescAttr($value = '', $data = array()){
		$status = [0 => '禁用', 1 => '正常'];
		return $status[$data['status']];
	}
	// 获取状态颜色类
	public function getStatusColorClassAttr($value, $data){
		$status = [0 => 'danger', 1 => 'primary'];
		return $status[$data['status']];
	}
	// 城市名称获取器
	public function getCityNameAttr($value, $data){
		$city_name = model('Area')->getNames($data['city_id']);
		return $city_name ? $city_name : '';
	}
	// 性别获取器
	public function getSexDescAttr($sex = '', $data = array()){
		$sex      = $sex ? $sex : $data['sex'];
		$sex_desc = get_type_desc($sex, 'sex_desc');

		return $sex_desc;
	}
	// 注册来源获取器
	public function getAppTypeDescAttr($app_type = '', $data = array()){
		$app_type      = $app_type ? $app_type : $data['app_type'];
		$app_type_desc = get_type_desc($app_type, 'app_type_desc');

		return $app_type_desc;
	}
	/**
	 * 可用豆子
	 * @param  string $user_id 用户ID
	 * @param  array  $data    用户数据
	 */
	public function getBeansAccountAttr($user_id = '', $data = array()){
		$user_id = $user_id ? $user_id : $data['user_id'];
		$beans_usable = model('UserAccount')->get_account_money($user_id, 'beans_usable');

		return $beans_usable ? intval($beans_usable) : 0;
	}
	/**
	 * 当前经验
	 * @param  string $user_id 用户ID
	 * @param  array  $data    用户数据
	 */
	public function getExperienceAccountAttr($user_id = '', $data = array()){
		$user_id = $user_id ? $user_id : $data['user_id'];
		$experience_usable = model('UserAccount')->get_account_money($user_id, 'experience_usable');

		return $experience_usable ? intval($experience_usable) : 0;
	}

	/**
	 * 用户登录
	 * @param  string $user_name 手机号/E-mail
	 * @param  string $password  密码
	 */
	public function login($user_name = '', $password = '', $app_type = '', $app_id = 0){
		if(!$user_name){
			$this->tips_info = '手机号/E-mail不能为空！';
			return false;
		}
		if(!$password){
			$this->tips_info = '密码不能为空！';
			return false;
		}

		// 手机号判断
		if(preg_match('/^1[34578][0-9]{9}$/', $user_name) == false && is_numeric($user_name)){
			$this->tips_info = '对不起，手机号不正确！';
			return false;
		}

		// 获取用户信息
		$info = $this->where(array('mobile' => $user_name))->whereOr(array('email' => $user_name))->find();
		$user_id = $info['user_id'];

		// 判断密码
		$password_md5 = password_md5_one($user_id, $password);
		if($info['password'] != $password_md5){
			$this->tips_info = '您的用户名或者密码有误！';
			return false;
		}
		// 判断是否禁用
		if($info['status'] == 0){
			$this->tips_info = '您的账号被禁用，请联系相关人员！';
			return false;
		}

		// 获取用户信息
		$user_info = $this->user_info($user_id);
		$user_info['token'] = $this->make_token($user_id, $app_type, $app_id);
		
		return $user_info;
	}
	public function user_info($user_id){
		$user = $this->where(array('user_id' => $user_id))->find();
		if(!$user){
			return false;
		}
		$area_model = model('Area');
		$user['province_name']   = $area_model->getNames($user['province_id']);
		$user['city_name']       = $area_model->getNames($user['city_id']);
		$user['area_name']       = $area_model->getNames($user['area_id']);
		$user['is_set_password'] = $user['password'] != '';

		$user['head_url']  = $user['head_url'];
		// 性别处理
		$user['sex_desc']  = $user['sex'];
		// 用户绑定信息
		$user['bind_info'] = $this->get_bind_sso_info($user_id);
		unset($user['password']);
		
		return $user;
	}

	/**
	 * 获取用户城市信息
	 * @param  [type] $user_id 用户ID
	 */
	public function get_user_city_info($user_id){
		$where['user_id'] = $user_id;
		$info = $this->field('province_id,city_id,area_id,user_type')->where($where)->find();

		$data['province_id'] = $info['province_id'] ? $info['province_id'] : 0;
		$data['city_id']     = $info['city_id'] ? $info['city_id'] : 0;
		$data['area_id']     = $info['area_id'] ? $info['area_id'] : 0;
		$data['user_type']   = $info['user_type'] ? $info['user_type'] : 'user';

		return $data;
	}
	/**
	 * 生成用户ID
	 */
	public function generate_user_id(){
		//随机生成9位数的用户ID
		$chars   = str_repeat('012356789', 3);
		$chars   = str_shuffle($chars);
		$user_id = substr($chars, 0, 9);
		//第一位为0的处理
		if(substr($user_id, 0, 1) == 0){
			$rand_id = str_shuffle(str_replace('0', '', $user_id));
			$user_id = substr($rand_id, 0, 1) . substr($user_id, 1);
		}
		//如果存在，再次生成ID
		if($this->is_exists($user_id)){
			return $this->generate_user_id();
		}
		return $user_id;
	}

	//获取用户TOKEN
	public function user_token(){
		return session('user_token');
	}
	/**
	 * 保存用户SESSION
	 * @param  string $user_info 用户信息
	 */
	public function save_session($user_info = ''){
		$time = 7 * 24 * 60 * 60;
		session(array('expire' => $time));
		//保存用户信息
		session('user_info', $user_info);
		//保存用户TOKEN
		session('user_token', $user_info['token']);
	}
	/**
	 * 清空登录SESSION
	 */
	public function clear_login_session(){
		session('user_info', null);
		session('user_token', null);

		return true;
	}
	/**
	 * 获取用户信息
	 */
	public function get_user_info($is_login = true){
		$user_id = $this->login_user_id($is_login);
		if(!$user_id){
			return false;
		}
		//获取用户信息
		$user_info = $this->user_info($user_id);
		$user_info['token'] = $this->get_token($user_id);
		$this->save_session($user_info);
		return $user_info;
	}
	/**
	 * 获取用户手机号
	 * @param  integer $user_id 用户ID
	 */
	public function get_user_mobile($user_id = 0){
		if(!$user_id){
			return '';
		}
		$mobile = $this->where(['user_id' => $user_id])->value('mobile');

		return $mobile ? $mobile : '';
	}
	/**
	 * 获取登录用户ID
	 * @param  boolean $is_login [description]
	 * @return [type]            [description]
	 */
	public function login_user_id($is_login = true){
		//获取token
		$token = session('user_token');
		if(!$token && $is_login){
			$this->login_timeout('对不起，您尚未登录！');
		}
		if(!$token){
			return 0;
		}
		$where['token'] = $token;
		$info = db('UserToken')->where($where)->field('user_id,create_time')->find();
		if(!$info && $is_login){
			$this->login_timeout('登录超时，请重新登录[1]！');
		}
		$conf_timeout = 7 * 24 * 60 * 60;
		$is_timeout = (time() - $info['create_time']) > $conf_timeout;
		if($is_timeout && $is_login){
			$this->login_timeout('登录超时，请重新登录[2]！');
		}
		if($is_login && $info){
			//刷新登录时间
			db('UserToken')->where($where)->update(array('create_time'=>time()));
		}
		
		return $info['user_id'] ? $info['user_id'] : 0;
	}
	/**
	 * 登录超时处理
	 */
	protected function login_timeout($msg = ''){
		$login_url = url('Login/index');
		$this->clear_login_session();
		if(request()->isAjax()){
			$this->json_error($msg ? $msg : $this->tips_info, array('url' => $login_url), 202);
		}
		session('login_jumpurl', request()->url(true));
		redirect($login_url)->send();
	}
	/**
	 * 返回错误信息
	 * @param  string $msg    [description]
	 * @param  [type] $data   [description]
	 * @param  [type] $status [description]
	 * @return [type]         [description]
	 */
	protected function json_error($msg = '', $data, $status = 400){
		$url = $data['url'];

		$info['msg']  = $msg;
		$info['data'] = $data;
		$info['code'] = $status;
		$info['url']  = $url ? $url : '';

		header('Content-Type:application/json; charset=utf-8');
		$json = json_encode($info, JSON_UNESCAPED_UNICODE);
		exit($json);
	}
	 /**
	 * 判断用户是否存在
	 * @param  [type]  $user_id 用户ID
	 * @return boolean          [description]
	 */
	public function is_exists($user_id){
		$where['user_id'] = $user_id;
		$count = $this->where($where)->count();
		return $count > 0;
	}
	/**
	 * 获取用户现有TOKEN
	 * @param  [type] $user_id   用户ID
	 * @return [type]            TOKEN
	 */
	public function get_token($user_id, $app_type = ''){
		$app_type = $app_type ? $app_type : isset($_SERVER['HTTP_APP_TYPE']) ? $_SERVER['HTTP_APP_TYPE'] : '';
		$app_type = $app_type ? $app_type : 'web';

		$where['user_id']   = $user_id;
		$where['app_type']  = $app_type;
		$token = db('UserToken')->where($where)->value('token');

		return $token ? $token : '';
	}
	/**
	 * 获取TOKEN的用户ID
	 * @param  string $token [description]
	 * @return [type]        [description]
	 */
	public function get_token_user_id($token=''){
		if(!$token){
			$get_token = $_REQUEST['token'];
			$app_token = $_SERVER['HTTP_APP_TOKEN'];
			$token     = $get_token ? $get_token : $app_token;
		}
		if(!$token){
			return 0;
		}
		$where['token'] = $token;
		$user_id = db('UserToken')->where($where)->value('user_id');
		return $user_id ? $user_id : 0;
	}
	/**
	 * 获取用户OPENID
	 * @param  [type] $user_id 用户ID
	 */
	public function get_user_openid($user_id, $sso_type = 'weixin'){
		$where['sso_type'] = $sso_type;
		$where['user_id']  = $user_id;
		$open_id = db('UserSso')->where($where)->value('open_id');
		return $open_id ? $open_id : '';
	}

	/**
	 * 获取第三方用户ID
	 * @param  [type] $open_id  [description]
	 * @param  string $sso_type [description]
	 * @return [type]           [description]
	 */
	public function get_sso_user_id($open_id, $sso_type='weixin'){
		$where['sso_type'] = $sso_type;
		$where['open_id']  = $open_id;
		$user_id = db('UserSso')->where($where)->value('user_id');
		return $user_id ? $user_id : '';
	}

	/**
	 * 是否绑定第三方账号
	 * @param  [type]  $user_id  用户ID
	 * @param  string  $sso_type 第三方类型，weixin微信
	 */
	public function is_bind($user_id,$sso_type='weixin'){
		$where['user_id']  = $user_id;
		$where['sso_type'] = $sso_type;
		$count = db('UserSso')->where($where)->count();
		return $count > 0;
	}
	/**
	 * 绑定第三方账号
	 * @param  string  $sso_type 第三方类型，weixin微信
	 * @param  integer $user_id  用户ID
	 * @param  string  $open_id  第三方用户ID
	 * @param  string  $nickname 第三方用户昵称
	 */
	public function sso_bind($sso_type = 'weixin', $user_id = 0, $open_id = '', $nickname = ''){
		if(!$sso_type){
			$this->tips_info = '对不起，第三方类型不能为空！';
			return false;
		}
		if(!$user_id){
			$this->tips_info = '对不起，用户ID不能为空！';
			return false;
		}
		if(!$open_id){
			$this->tips_info = '对不起，第三方用户唯一标识不能为空！';
			return false;
		}

		//判断用户是否有绑定
		$is_bind = $this->get_sso_user_id($open_id, $sso_type);
		if($is_bind){
			$sso_name_arr['weixin'] = '微信';
			$sso_name_arr['weibo']  = '微博';
			$sso_name = $sso_name_arr[$sso_type];
			$this->tips_info = '对不起，您的' . $sso_name . '账号' . ($nickname ? '(' . $nickname . ')' : '') . '已被平台其他用户绑定了！';
			return false;
		}

		//创建第三方账号
		$data['user_id']     = $user_id;
		$data['sso_type']    = $sso_type;
		$data['open_id']     = $open_id;
		$data['nickname']    = $nickname ? $nickname : '';
		$data['create_time'] = time();
		db('UserSso')->insert($data);
		
		return true;
	}
	/**
	 * 解除第三方绑定
	 * @param  string  $sso_type 第三方类型，weixin微信
	 * @param  integer $user_id  用户ID
	 */
	public function sso_unbind($sso_type = '', $user_id = 0){
		if(!$sso_type){
			$this->tips_info = '第三方类型不能为空！';
			return false;
		}
		if(!$user_id){
			$this->tips_info = '用户ID不能为空！';
			return false;
		}

		$where['user_id'] = $user_id;
		$user_info = $this->where($where)->find();
		if(!$user_info['mobile']){
			$this->tips_info = '您为第三方登录账号，无法取消绑定！';
			return false;
		}
		if(!$user_info['password']){
			$this->tips_info = '您的账号尚未设置密码，无法解除绑定！';
			return false;
		}
		//判断用户是否有绑定
		if($this->is_bind($user_id, $sso_type)){
			$where['user_id']  = $user_id;
			$where['sso_type'] = $sso_type;
			db('UserSso')->where($where)->delete();
			return true;
		}else{
			$this->tips_info = '您尚未绑定，不能解除绑定！';
			return false;
		}
	}
	/**
	 * 第三方登录
	 * @param  string  $sso_type    第三方类型
	 * @param  string  $open_id     第三方用户ID
	 * @param  string  $nickname    用户呢称
	 * @param  boolean $is_auto_reg 是否自动注册
	 */
	public function sso_login($sso_type = 'weixin', $open_id = '', $nickname = '', $is_auto_reg = false, $app_type = 'web', $app_id = 0){
		if(!$sso_type){
			$this->tips_info = '第三方类型不能为空！';
			return false;
		}
		if(!$open_id){
			$this->tips_info = 'OPEN_ID不能为空！';
			return false;
		}
		$user_id = $this->get_sso_user_id($open_id, $sso_type);
		if(!$user_id && !$is_auto_reg){
			$this->tips_info = '您尚未绑定，无法使用第三方登录！';
			return false;
		}
		// 未绑定注册的，创建账号并绑定
		if(!$user_id && $is_auto_reg){
			// 生成用户ID
			$user_id = $this->generate_user_id();
			$area_model = model('Area');
			// 设置省份
			if($province_name = $this->getParams('province_name')){
				$city_info['province_id'] = $area_model->get_name_id($province_name, 1);
			}
			// 设置城市
			if($city_name = $this->getParams('city_name')){
				$city_info['city_id'] = $area_model->get_name_id($city_name, 2);
			}
			// 获取IP地址城市信息
			$city_info = $city_info ? $city_info : $area_model->ip2city();
			if($city_info['city_id'] && $city_info['province_id']){
				$data['province_id'] = $city_info['province_id'];
				$data['city_id']     = $city_info['city_id'];
			}
			// 用户头像
			if($head_url = $this->getParams('head_url')){
				// $data['head_id'] = D('File')->down_remote_img($this->head_url, 'head', $user_id);
				$data['sso_head_url'] = $head_url;
			}
			// 性别
			if($sex = $this->getParams('sex')){
				$data['sex'] = $sex;
			}
			// 昵称过滤
			$nickname = model('Config')->name_filter($nickname);
			$data['user_id']     = $user_id;
			$data['app_type']    = $app_type ? $app_type : 'system';
			$data['nickname']    = $nickname ? $nickname : $user_id;
			$data['create_time'] = time();
			$this->insert($data);
			$this->sso_bind('weixin', $user_id, $open_id, $nickname);
		}
		//获取用户信息
		$user_info = $this->user_info($user_id);
		if(!$user_info){
			$this->tips_info = '找不到用户信息！';
			return false;
		}
		$user_info['token'] = $this->make_token($user_id, $app_type, $app_id);

		return $user_info;
	}
	/**
	 * 获取用户绑定第三方信息
	 * @param  [type] $user_id [description]
	 * @return [type]          [description]
	 */
	public function get_bind_sso_info($user_id){
		$data = array();
		$sso_bind = array('weibo', 'weixin', 'qq');
		foreach ($sso_bind as $type) {
			$where['user_id']  = $user_id;
			$where['sso_type'] = $type;
			$info = db('UserSso')->where($where)->find();
			$data['is_bind_' . $type] = $info['open_id'] != '';
			$data['nickname_' . $type] = $info['nickname'] ? $info['nickname'] : '';
		}
		return $data;
	}

	/**
	 * 生成用户TOKEN
	 * @param  string  $user_id   用户ID
	 * @param  integer $app_type  登录类型 web、wap、ios、android
	 * @param  integer $app_id    APPID，默认为0
	 * @param  integer $imei      设备唯一标识
	 * @param  integer $device    设备信息 如iPhone 5s
	 */
	public function make_token($user_id = '', $app_type = '', $app_id = 0, $imei = '', $device = ''){
		$token_model = db('UserToken');
		$imei        = $imei ? $imei : $_SERVER['HTTP_APP_IMEI'];
		$app_type    = $app_type ? $app_type : $_SERVER['HTTP_APP_TYPE'];
		$device      = $device ? $device  : $_SERVER['HTTP_APP_DEVICE'];
		$app_id      = $app_id ? $app_id : 0;

		$app_type = $app_type ? $app_type : 'web';
		//踢出其它设备登录用户
		$where['user_id']  = $user_id;
		$where['app_type'] = $app_type;//退出相同设备登录
		$where['app_id']   = $app_id;//应用ID
		// $where['app_type'] = array('neq','web');//处理APP登录
		// 处理WEB登录
		// if($app_type == 'web'){
		// 	$where['app_type'] = 'web';
		// }
		$token_model->where($where)->update(array('create_time' => 0));

		unset($where);
		$where['user_id']  = $user_id;
		$where['app_type'] = $app_type;
		$where['app_id']   = $app_id;
		$old_token = $token_model->where($where)->value('token');

		$token = md5($user_id . $app_type . $app_id .uniqid());

		$data['app_type']    = $app_type;
		$data['user_id']     = $user_id;
		$data['app_id']      = $app_id;
		$data['token']       = $token;
		$data['ip']          = request()->ip();
		$data['create_time'] = time();
		//设备信息
		$data['device'] = $device ? $device : '';
		//设备唯一标识
		$data['imei']   = $imei ? $imei : '';

		if($old_token){
			$where['token'] = $old_token;
			$token_model->where($where)->update($data);
		}else{
			$token_model->insert($data);
		}
		return $token;
	}

	/**
	 * 判断是否收藏
	 * @param  [type]  $user_id   用户ID
	 * @param  [type]  $object_id 收藏对应ID
	 * @param  string  $fav_type  收藏类型
	 */
	public function is_fav($user_id = 0, $object_id = 0, $fav_type = 'article'){
		$where['user_id']   = $user_id;
		$where['object_id'] = $object_id;
		$where['fav_type']  = $fav_type;

		$count = db('UserFav')->where($where)->count();

		return $count > 0;
	}
	/**
	 * 设置收藏
	 * @param [type] $user_id    用户ID
	 * @param [type] $object_id  收藏ID
	 * @param string $fav_type   收藏类型
	 * @param string $is_save    只保存，不取消
	 */
	public function set_fav($module_name = 'Article', $field = 'fav_num', $where_filed = 'article_id', $user_id, $object_id, $fav_type = 'article', $is_save = false){
		if(!$module_name){
			$this->tips_info = '模块名称不能为空！';
			return false;
		}
		if(!$field){
			$this->tips_info = '更新字段不能为空！';
			return false;
		}
		if(!$where_filed){
			$this->tips_info = 'where字段不能为空！';
			return false;
		}
		if(!$user_id){
			$this->tips_info = '用户ID不能为空！';
			return false;
		}
		if(!$object_id){
			$this->tips_info = 'object_id不能为空！';
			return false;
		}
		$tips_info = '';
		$is_fav = $this->is_fav($user_id, $object_id, $fav_type);
		$this->is_fav = $is_fav;

		$where['user_id']   = $user_id;
		$where['object_id'] = $object_id;
		$where['fav_type']  = $fav_type;
		if($is_fav && $is_save == false){
			db($module_name)->where(array($where_filed => $object_id))->setDec($field);
			db('UserFav')->where($where)->delete();
			$this->tips_info = $tips_info ? $tips_info : '取消收藏成功！';
			// 收藏数量
			$this->_total_fav_num = model($module_name)->where(array($where_filed => $object_id))->value($field);
			return 2;//取消收藏
		}
		if(!$is_fav){
			db($module_name)->where(array($where_filed => $object_id))->setInc($field);
			$data = $where;
			$data['create_time'] = time();
			db('UserFav')->insert($data);
			$this->tips_info = $tips_info ? $tips_info : '收藏成功！';
			// 收藏数量
			$this->_total_fav_num = model($module_name)->where(array($where_filed => $object_id))->value($field);
			return 1;//添加收藏
		}
		if($is_save){
			$this->tips_info = '已推荐';
			$this->_total_fav_num = model($module_name)->where(array($where_filed => $object_id))->value($field);
			return 1;
		}

		$this->tips_info = '异常';
		return 0;
	}
	/**
	 * 获取用户收藏数量
	 * @param  [type] $user_id  用户ID
	 * @param  string $fav_type 收藏类型
	 */
	public function get_fav_num($user_id, $fav_type = 'article'){
		$where['user_id'] = $user_id;
		if($fav_type){
			$where['fav_type'] = $fav_type;
		}
		$count = D('UserFav')->where($where)->count();

		return $count ? $count : 0;
	}
	/**
	 * 获取用户收藏对应ID
	 * @param  [type] $user_id  用户ID
	 * @param  string $fav_type 收藏类型
	 */
	public function get_fav_object_ids($user_id, $fav_type = 'article'){
		$where['user_id'] = $user_id;
		if($fav_type){
			$where['fav_type'] = $fav_type;
		}
		$object_id_arr = db('UserFav')->where($where)->order('fav_id desc')->column('object_id');
		$object_id_str = implode(',', $object_id_arr);
		$object_id_str = $object_id_str ? $object_id_str : 0;

		return $object_id_str;
	}
	/**
	 * 获取收藏用户ID
	 * @param  [type] $user_id  对象ID
	 * @param  string $fav_type 收藏类型
	 */
	public function get_fav_user_ids($object_id, $fav_type = 'article', $is_return_array = false){
		$where['object_id'] = $object_id;
		if($fav_type){
			$where['fav_type'] = $fav_type;
		}
		$user_id_arr = db('UserFav')->where($where)->order('fav_id desc')->column('user_id');
		// 返回数组
		if($is_return_array){
			return $user_id_arr ? $user_id_arr : array();
		}
		// 返回字符串
		$user_id_str = implode(',', $user_id_arr);
		$user_id_str = $user_id_str ? $user_id_str : 0;

		return $user_id_str;
	}
	/**
     * 判断用户手机号是否存在
     * @param  [type]  $mobile 手机号
     * @return boolean         [description]
     */
    public function mobile_exists($mobile){
    	$where['mobile'] = $mobile;
    	$count = $this->where($where)->count();
    	return $count > 0;
    }
    /**
	 * 检查密码
	 * @param  [type] $user_id  用户ID
	 * @param  string $password 密码，MD5一次小写
	 */
	public function check_password($user_id, $password = ''){
		if(!$user_id){
			$this->tips_info = '用户ID不能为空！';
			return false;
		}
		if(!$password){
			$this->tips_info = '密码不能为空！';
			return false;
		}
		// 获取原密码
		$db_password = $this->where(array('user_id' => $user_id))->value('password');
		if(!$db_password){
			$this->tips_info = '对不起，您输入尚未设置密码！';
			return false;
		}
		// 验证密码
		$check_password = password_md5_one($user_id, $password);
		// 验证输入密码是否正确
		if($check_password != $db_password){
			$this->tips_info = '对不起，您输入密码不对！';
			return false;
		}
		return true;
	}
    /**
	 * 修改手机号
	 * @param  [type] $user_id 用户ID
	 * @param  [type] $mobile  手机号
	 */
	public function change_mobile($user_id, $mobile){
		if(!$user_id){
			$this->tips_info = '用户ID不能为空！';
			return false;
		}
		//手机号判断
		if(preg_match('/^1[34578][0-9]{9}$/', $mobile) == false){
			$this->tips_info = '对不起，手机号不正确！';
			return false;
		}
		if($this->mobile_exists($mobile)){
			$this->tips_info = '您输入的手机号已经注册过，无法绑定！';
			return false;
		}
		//清空验证码缓存
		cache('API_SMSCODE_' . $mobile, null);
		
		$data['mobile'] = $mobile;
		$this->where(array('user_id' => $user_id))->update($data);

		return true;
	}
	/**
	 * 修改E-mail
	 * @param  [type] $user_id 用户ID
	 * @param  [type] $email   E-mail
	 */
	public function change_email($user_id, $email){
		if(!$user_id){
			$this->tips_info = '用户ID不能为空！';
			return false;
		}
		//E-mail判断
		if (!preg_match("/([\w\-]+\@[\w\-]+\.[\w\-]+)/", $email)) {
			$this->tips_info = '无效的 email 格式！';
			return false;
		}
		if($this->email_exists($email)){
			$this->tips_info = '您输入的E-mail已经注册过，无法绑定！';
			return false;
		}

		$data['email'] = $email;
		$this->where(array('user_id' => $user_id))->update($data);

		return true;
	}
	/**
	 * 修改密码
	 * @param  [type] $user_id 			用户ID
	 * @param  [type] $old_password   	旧密码
	 * @param  [type] $new_password   	新密码
	 */
	public function change_password($user_id, $old_password = '', $new_password = ''){
		if(!$user_id){
			$this->tips_info = '用户ID不能为空！';
			return false;
		}
		$where['user_id'] = $user_id;
		$info = $this->field('password')->where($where)->find();
		//判断旧密码是否正确
		$db_password  = $info['password'];
		$password_md5 = password_md5_one($user_id, $old_password);
		if($db_password != $password_md5 && $db_password){
			$this->tips_info = '您输入的旧密码有误！';
			return false;
		}

		//更新新密码
		$password_new_md5 = password_md5_one($user_id, $new_password);
		$data['password'] = $password_new_md5;
		$this->where($where)->update($data);

		return true;
	}
	/**
	 * 活跃用户
	 * @param  integer $limit 数量
	 */
	public function get_active_list($limit = 10){
		$where['status'] = 1;
		$list = model('UserData')->where($where)->order('experience desc,beans desc,question_num desc,answer_num desc')->limit($limit)->select();

		return $list;
	}

	/**
	 * 用户头像裁切
	 * @param  [type]  $user_id [description]
	 * @param  [type]  $file_id [description]
	 * @param  integer $x1      [description]
	 * @param  integer $y1      [description]
	 * @param  [type]  $x2      [description]
	 * @param  [type]  $y2      [description]
	 * @param  [type]  $width   [description]
	 * @param  [type]  $height  [description]
	 * @return [type]           [description]
	 */
	public function user_head_crop($user_id, $file_id, $x1 = 0, $y1 = 0, $x2, $y2, $width, $height){
		if(!$user_id){
			$this->tips_info = '用户ID不能为空！';
			return false;
		}
		if(!$file_id){
			$this->tips_info = '请选择图片！';
			return false;
		}
		$x1 = $x1 ? $x1 : 0;
		$y1 = $y1 ? $y1 : 0;
		if(!$x2){
			$this->tips_info = 'x2不能为空';
			return false;
		}
		if(!$y2){
			$this->tips_info = 'y2不能为空';
			return false;
		}
		if(!$width){
			$this->tips_info = 'width不能为空';
			return false;
		}
		if(!$height){
			$this->tips_info = 'height不能为空';
			return false;
		}
		
		$info = model('File')->find($file_id);
		if(!$info){
			$this->tips_info = '文件不存在！';
			return false;
		}
		if(!in_array(strtolower($info['ext']), model('File')->getAllowExt('img'))){
			$this->tips_info = '[' . $info['ext'] . ']此图片文件格式无法裁剪！';
			return false;
		}
		$crop_file_id = model('File')->crop($user_id, $file_id, $x1, $y1, $x2, $y2, $width, $height);
		if($crop_file_id){
			//更新头像
			$this->where(array('user_id' => $user_id))->update(array('head_id' => $crop_file_id));
			$data = model('File')->find($crop_file_id);
			return $data;
		}
		$this->tips_info = '裁剪失败！';
		return false;
	}

	// 用户关注时间
	public function getUserFocusTimeAttr($user_id = 0, $data = []){
		$user_id  = $user_id ? $user_id : $data['user_id'];
		$_user_id = $this->user_id();
		
		$where['user_id']   = $_user_id;
		$where['fav_type']  = 'user_focus';
		$where['object_id'] = $user_id;
		$time = db('UserFav')->where($where)->value('create_time');

		return $time > 0 ? $time : 0;
	}
	
}